import { jumpUrl, useUrlParams } from '@/utils';
import { message } from 'antd';
import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';
import CryptoJS from 'crypto-js';
import JSEncrypt from 'encryptlong';
import jsrsasign from 'jsrsasign';
import md5 from 'md5';
import { getLocale } from 'umi';

const proxyPrefix = process.env.NODE_ENV == 'production' ? 'https://api.xlend.hk' : '/api';

const whiteList = [`${proxyPrefix}/web/checkRegister`];
export const useGetToken = () => {
  const urlAction = `${proxyPrefix}/web/fileUpload`;

  const { token = '' } =
    useUrlParams('token') || JSON.parse(localStorage.getItem('userInfo') || '{}');
  return {
    urlAction,
    token,
  };
};
const request = axios.create({
  baseURL: proxyPrefix,
});
const apiKey = 'eadc675f2cbe5dfa';
// 私钥
const RSAPrivateKey =
  'MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMD9eLmRH/s/HNaXzS74acE+D+7TobkxvL9XV/l+zGsoxv6zEHqJAFLRWxxP8BWoyS3YdcLumhYwqGe5Y+ZVaCbhSsIIT26RljOlRtjjC1V0SnZaADZfBHWKsa/Iizij5XugXNzJGt5F8aW92rYbzeZN/9DhtwlMNynLw6fsnwRDAgMBAAECgYEAoGsRis6DUwknI4mTWNPMtICuJctsxs/9IN+tlQo9SWXf459ctz5iMnUr0uDvpFFkyOMBIEPNeVyA35dO3wtnQljDyywo8cNLQsAIAg2wvMu0N8SKZm5XxOSptrrxirg2ZZOp1YIN94rOo3Ck+1h/V9kwJL/BHy6yfXR4hrCZJ8ECQQDfW7rnC3c/Q4Xq8ts2ZK5Idet+TQfSzpIO5zwgu/ZcrRUzMGLajEfi8MlMyN3SqExpbeEMOOrPHtdi7cZtVfeJAkEA3TGbqoqY4grE+7+YcXH9fHc8OcUjV039hAfT5PmB4UI5AKjtcQzSiMtfT8cbYpEjgVIN/DmbqRdwDsS5DxqeawJBAI4ea9o/LW0PpdJNHLaLcWmhvmnq0aOM1Nquv0+EyclGSEr96qhswgDgfPViieJUO+qJg7ynKqEHWr0T1kIThSECQQC/vUL9QItqVn+O4vTYUkGz5QAV6+fIxFhgXRC3SfnmNCuJgOXiu4S9A94pH6WDeeDXNzPcUmu21hRTGQB6MU7lAkBIL2GEGwocXXm/wA1xO23yZUQ1dkBOnKuFGc5FrEW2g6qSqQS8gugTRoXSa+gRnRR12MSfh8z8PZH51E9c/MVO';

function encrypt(params: object, aes?: boolean, rsaKey?: string) {
  // 加签
  const obj: any = {};
  obj.data = JSON.stringify(params);
  if (aes) {
    const d = CryptoJS.enc.Utf8.parse(obj.data);
    const k = CryptoJS.enc.Utf8.parse(apiKey as any);
    const aesData = CryptoJS.AES.encrypt(d, k, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs8,
    }).toString();
    obj.data = aesData;
  }
  let s = '';
  for (const i in obj) {
    s = s + i + '=' + obj[i] + '&';
  }
  s = s.slice(0, s.length - 1);
  // 私钥加签
  let rsa: any = new jsrsasign.RSAKey();
  const rsk: string = rsaKey ?? RSAPrivateKey;

  rsa = jsrsasign.KEYUTIL.getKey(
    '-----BEGIN PRIVATE KEY-----\n' + rsk + '\n-----END PRIVATE KEY-----',
  );
  const sig = new jsrsasign.KJUR.crypto.Signature({
    alg: 'SHA256withRSA',
    prov: 'cryptojs/jsrsa',
  } as any);
  sig.init(rsa);
  sig.updateString(s);
  const sign = jsrsasign.hextob64(sig.sign());
  obj.sign = sign;

  const result = obj;
  return result;
}
function decrypt(target: string, rsaKey?: string) {
  const decrypt = new JSEncrypt();

  const rsk: string = rsaKey ?? RSAPrivateKey;
  decrypt.setPrivateKey(rsk);

  const result = decrypt.decryptLong(JSON.stringify(target));

  return JSON.parse(result);
}
const getLanguage = (lang: string) => {
  switch (lang) {
    case 'en-US':
      return 'en_US';
    case 'zh-TW':
      return 'zh_TW';
    default:
      return lang;
  }
};

request.interceptors.request.use((config: any) => {
  const timestamp = new Date().getTime(); // 13位
  const { token = '', ti } =
    useUrlParams('token') || JSON.parse(localStorage.getItem('userInfo') || '{}');
  const newTi = parseInt(useUrlParams('ti') || ti || 0);
  if (config.headers) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token}`,
      sign: md5(apiKey + (timestamp + newTi)),
      timestamp: timestamp + newTi,
      lang: useUrlParams('lang') || getLanguage(getLocale()),
      source: 'H5',
    };
  }
  return config;
});

request.interceptors.response.use(
  (response): any => {
    const data: API.ResponseStructure<any> = response?.data;
    const cUrl = `${proxyPrefix}${response.config.url}`;
    if ((cUrl || '').includes(`${proxyPrefix}/web/download/`)) {
      return Promise.resolve(response);
    }
    if (whiteList.includes(cUrl)) {
      return Promise.resolve(response.data);
    }
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    const { code, message: info } = data;

    if (['100401', '100501'].includes(code)) {
      localStorage.setItem('userInfo', '{}');
      jumpUrl('/login');
      // message.error({
      //   content: info || 'Request error',
      // });
    } else if (code === '100200') {
      return Promise.resolve(data);
    } else {
      message.error({
        content: info || 'Request error',
        key: '1',
      });

      return Promise.reject(data);
    }
  },

  () => {
    message.error({
      content: 'Request error',
      key: '2',
    });
  },
);

//
// 泛型T用来指定Reponse类型中result的类型
export default <T>(config: AxiosRequestConfig) => {
  let newConfig = {};

  if ((`${proxyPrefix}${config.url}` || '').includes(`${proxyPrefix}/web/download/`)) {
    newConfig = config;
  } else {
    newConfig = {
      ...config,
      data: encrypt(config.data ? config.data : {}, false, RSAPrivateKey),
    };
  }

  // 指定promise实例成功之后的回调函数的第一个参数的类型为Response<T>
  return new Promise<API.ResponseStructure<T>>((resolve, reject) => {
    request
      .request<AxiosResponse<API.ResponseStructure<T>>>(newConfig)
      .then((response: any) => {
        const data = response?.data;
        const newData = {
          ...response,
          data: typeof data == 'string' ? decrypt(data) : data,
        };
        resolve(newData);
      })
      .catch((error) => {
        // 请求失败的处理
        reject(error);
      });
  });
};
